<template>
  <view v-if="show" class="goods-found box-package">
    <view v-if="goodsList && goodsList.length" class="h4 title">搭配礼包</view>
    <view class="packageIntroIteBox">
      <view v-for="(item, index) in goodsList" :key="index" class="packageIntroIte">
        <view class="product-info">
          <view class="product-box" @click="navigateToDeatil(item)">
            <view class="product-img">
              <b-image :src="item.goodsImage" width="140" height="140" />
            </view>
            <view class="product-intro">
              <view class="p">{{ item.goodsName }}</view>
              <view v-if="type === 'calculate'" class="b" style="font-size: 26rpx;line-height:30rpx;">
                <!-- <view>{{ item.freightMsg }}</view> -->
                <block v-if="item.freightList">
                  <view v-for="(text, i) in item.freightList" :key="i">
                    {{ text }}
                    <view v-if="i === 0 && item.freightData && item.freightData.freightIntervalDetails && item.freightData.freightIntervalDetails.length" class="wh_icon" @click.stop.prevent="showFreightRulePopup(item.freightData.freightIntervalDetails)">
                      <image src="/static/images/inventory/question_icon_gray.png" />
                    </view>
                  </view>
                </block>
                <view v-else>{{ item.freightMsg }}</view>
              </view>
              <view v-else class="b">
                ¥{{ item.regionPrice.toFixed(2) }} <view class="i">/单位</view>
                <view class="small">¥{{ item.ordinaryPrice.toFixed(2) }}/单位</view>
              </view>
            </view>
          </view>
          <view v-if="type !== 'calculate' || (type === 'calculate' && item.freightMsg !== '该地区暂不支持配送')" class="clicksc">
            <base-stepper :value.sync="item.count" :size="42" :min="0" :max="999" border-radius="5" @change="changeQuantity($event, item)" />
          </view>

          <view v-if="item.presentGoods.length && type !== 'calculate'" class="present">
            <view class="small">赠品：</view>
            <view v-for="(i, k) in item.presentGoods" :key="k" class="span">
              {{ i.giveRemark || '' }}
            <!-- {{ i.name }}
            <view class="small">(满{{ i.buyNum }}单位赠{{ i.giveNum }})
              <view class="i">x{{ Math.floor(item.count / i.buyNum) }}</view>
            </view> -->
            </view>
          </view>

        </view>
      </view>
    </view>

    <view v-if="markupGoodses.length" class="addPurchaseBox">
      <view class="form-title">
        <text>加小钱得好礼</text>
        <text class="title-tip">（加购商品只可选择一种）</text>
      </view>
      <view class="form-content">
        <view v-for="(item, index) in markupGoodses" :key="index" class="gifts-item">
          <view class="goods-item">
            <image class="icon_gou" :src="index === current ? '/static/images/icon/icon_radio_active.png' :'/static/images/icon/icon_radio.png'" @click.stop="selEvent(index)" />
            <view class="img-con">
              <b-image :src="item.image" mode="aspectFill" />
              <!-- <image v-if="item.status === 5" src="/static/images/common/img_status_5.png" class="drop-img" mode="aspectFit" /> -->
            </view>
            <view class="goods-content">
              <view :class="['title', {'gray-text':current !== index || item.status === 5}]">{{ item.name }}</view>
              <view :class="['goods-sku', {'gray-text':current !== index || item.status === 5}]" @click.stop="goSelSku(index, true)">
                <text v-if="item.skuName">{{ item.skuName }}</text>
                <text v-else>请选择规格</text>
                <image class="right-icon" src="/static/images/inventory/arrow_left.png" mode="aspectFit" />
              </view>
              <view class="money-item">
                <view class="text-flex">
                  <view v-if="item.status === 5" class="drop-text">已下架</view>
                  <text :class="{'gray-text':current !== index || item.status === 5}">￥<text :class="['big-money', {'gray-text':current !== index || item.status === 5}]">{{ item.price | formatMoney }}</text></text>
                </view>
                <base-stepper v-if="index === current" :value="item.count" :min="1" :max="item.selectedSkuItem && item.selectedSkuItem.order_min ? item.selectedSkuItem.order_min : 999999" :size="34" :border-radius="4" @change="addQuantityChange($event,index)" @disable="alertMax"></base-stepper>
                <base-stepper v-else :value="0" :min="0" :max="0" :size="34" :border-radius="4"></base-stepper>
              </view>
            </view>
          </view>
          <view v-if="item.limit_buy_tips" :class="['gift-tips', {'gray-area':current !== index || item.status === 5}]">
            <view class="title">
              {{ item.limit_buy_tips }}
            </view>
          </view>
        </view>
      </view>
    </view>
    <view v-if="packageTotal && type !== 'calculate'" class="total-info">
      <view class="num">共{{ packageTotal.main }}款{{ packageTotal.box }}箱</view>
      <view class="money"><view class="b">会员价￥{{ packageTotal.vip.toFixed(2) }}</view></view>
    </view>
    <base-popup :show="pShow" whole-mask :show-close="false" @close="closePopup">
      <view
        v-if="selGoods && selGoods.sku_list && hold"
        class="maskContainer singleGoodsShopCartMask"
        @touchmove.prevent>
        <view class="cartClose" @click="closePopup">
          <image src="/static/images/icon/icon_close.png" />
        </view>
        <view class="cartMain">
          <view class="goodsImg">
            <b-image width="180" mode="aspectFill" height="180" :src="selectedSkuItem ? selectedSkuItem.goods_pic : selGoods.image" />
          </view>
          <view class="priceBox">
            <view class="price">
              <view class="span"><view class="b">¥</view>{{ (_getUserLevel(selectedSkuItem || selGoods)) | formatMoney }}</view>
            </view>
            <view class="skuDec">{{ selectedSkuItem ? `已选择: "${selectedSkuItem.selectText ? selectedSkuItem.selectText + ';' : ''}  ${buyCount}件"` : '请选择' }}</view>
          </view>
        </view>
        <sku-list :sku-origin="selGoods" :sku-list="selGoods.sku_list" @selectedItem="changeSkuItem"></sku-list>
        <view class="cartCount">
          <view class="title">购买数量
            <view v-if="selectedSkuItem && selectedSkuItem.order_limit !== 0" class="small">
              (限购{{ selectedSkuItem.order_limit }}件)
            </view>
          </view>
          <view style="height: 42rpx">
            <base-stepper :value="buyCount" :border-radius="0" :size="42" :min="1" :max="selectedSkuItem && selectedSkuItem.order_min ? selectedSkuItem.order_min : 999999" @change="addQuantityChange($event)" @disable="alertMax"></base-stepper>
          </view>
        </view>
        <view class="cartBut maskBottomBtn" :class="{'gray': !selectedSkuItem}" @click="cartConfirm">确认</view>
      </view>
    </base-popup>
  </view>
</template>

<script>
import BaseStepper from '@/components/base/base-stepper'
import SkuList from './commodity-sku.vue'
import { getUserLevel } from '@/utils/common'
export default {
  name: 'CommodityBonusGift',
  components: { BaseStepper, SkuList },
  props: {
    allData: {
      type: Object,
      required: true,
      default: null
    },
    type: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      goodsList: [],
      selGoods: {},
      markupGoodses: [], // 加价购商品列表
      current: -1, // 当前勾选加购商品下标
      pShow: false,
      selectedSkuItem: {}, // 当前选中的sku项数据
      buyCount: 1, // 规格选择弹窗中的商品数
      maskType: 'singleGoods',
      hold: true,
      show: false
    }
  },
  computed: {
    packageTotal() {
      let mainNum = 0
      let boxNum = 0
      let commonPrice = 0
      let vipPrice = 0
      this.goodsList.filter(item => {
        if (item.count > 0) {
          mainNum += 1
          boxNum += item.count
          commonPrice += item.count * item.ordinaryPrice
          vipPrice += item.count * item.regionPrice
        }
      })
      const res = this.goodsList.filter(item => item.count > 0)
      const param = {
        main: mainNum,
        box: boxNum,
        common: commonPrice,
        vip: vipPrice,
        selected: res
      }
      return param
    }
  },
  created() {
    if (!this.allData && !this.allData.gifts) return []
    const temp = this.allData.gifts.map(item => {
      item.count = 0
      if (item.freightMsg) {
        item.freightList = item.freightMsg.split('\n')
      }
      return item
    })
    const list = JSON.stringify(temp)
    this.goodsList = JSON.parse(list)
    if (this.allData.markup_goodses) {
      this.allData.markup_goodses.map(item => {
        if (item.sku_list.length === 1) {
          item.skuName = item.sku_list[0].properties_name.split(';').reduce((a, b) => a.split(':')[1] + '; ' + b.split(':')[1])
        }
      })
      this.markupGoodses = this.allData.markup_goodses.concat() || []
    }
    this.show = true
  },
  methods: {
    setFreightData(data) {
      this.goodsList.map((sitem, sindex) => {
        sitem.freightData = null
        return sitem
      })
      if (!data) return
      for (const iterator in data.freight_calcu_map) {
        this.goodsList = this.goodsList.map((sitem, sindex) => {
          if (iterator === sitem.goodsId) {
            sitem.freightData = data.freight_calcu_map[iterator]
            sitem.freightList = sitem.freightData.freightText.split('\n')
          }
          return sitem
        })
      }
    },
    setGoodsList(data) {
      data.gifts.map((item, index) => {
        this.goodsList.map((sitem, sindex) => {
          if (item.freightMsg && sindex === index) {
            sitem.freightMsg = item.freightMsg
            sitem.freightList = item.freightMsg.split('\n')
          }
          return item
        })
      })
    },
    navigateToDeatil(item) {
      this.$navigateTo(`/pagesDetail/commodity/index?box_id=${item.boxId}&from_type=11&series_id=${''}&type=boxGoods&hideMenu=true`)
    },
    changeQuantity(num, item) {
      this.$set(item, 'count', num)
      this.$emit('calculTotal', this.calcuTotal())
      if (this.current === -1) return
      const markupGoodItem = this.markupGoodses[this.current]
      const maxNum = Math.floor(this.packageTotal.box / markupGoodItem.buy_num) * markupGoodItem.additional_num
      if (maxNum === 0) {
        uni.showToast({
          title: '礼包数量减少，加购商品已清除',
          icon: 'none'
        })
        this.markupGoodses[this.current].count = 0
        this.current = -1
        return
      }
      if (maxNum < markupGoodItem.count) {
        uni.showToast({
          title: '礼包数量减少，加购商品数量已变更',
          icon: 'none'
        })
        this.markupGoodses[this.current].count = maxNum
      }
    },
    // 点击规格事件
    changeSkuItem(item, flag) {
      if (item) {
        if (item && item.order_limit > 0) {
          item.order_min = Math.min(item.order_limit, item.num)
        } else {
          item.order_min = item.num
        }
        this.markupGoodses[this.current].skuName = item.selectText
        if (item.order_min < this.markupGoodses[this.current].count) {
          this.markupGoodses[this.current].count = 1
          this.buyCount = 1
        }
      } else {
        this.markupGoodses[this.current].skuName = '请选择规格'
      }
      this.selectedSkuItem = item
      this.markupGoodses[this.current].selectedSkuItem = item
    },
    // 改变加购商品数量
    addNumChange(e, index) {
      this.markupGoodses[index].count = e
      this.$set(this, 'buyCount', e)
    },
    addQuantityChange(num) {
      this.$set(this, 'buyCount', num)
      if (this.current === -1) return
      this.markupGoodses[this.current].count = num
      this.checkOutMax(num)
    },
    checkOutMax(num) {
      const item = this.markupGoodses[this.current]
      if (Number(num) > item.selectedSkuItem.order_min) return
      const maxNum = Math.floor(this.packageTotal.box / item.buy_num) * item.additional_num
      let number = num
      if (maxNum < num) {
        uni.showToast({
          title: '已到达加购上限，请先添加礼包活动数量',
          icon: 'none'
        })
        number = maxNum
      }
      this.$nextTick(() => {
        this.markupGoodses[this.current].count = number
        this.$set(this, 'buyCount', number)
      })
    },
    // 改变商品数量
    cartConfirm() {
      this.closePopup()
    },
    closePopup() {
      const addItem = this.markupGoodses[this.current]
      if (!(addItem.selectedSkuItem && addItem.selectedSkuItem.sku_code)) {
        this.current = -1
      }
      this.$set(this, 'pShow', false)
    },
    _getUserLevel(item) {
      if (item) {
        return item[getUserLevel()] || item.price || 0
      }
      return 0
    },
    checkBuyRole() {
      if (!this.allData.goods || !this.allData.goods.price) return
      if (this.packageTotal.vip < this.allData.goods.price) {
        uni.showToast({
          title: '礼包金额需满' + this.allData.goods.price + '元，请先选择礼包商品',
          icon: 'none',
          duration: 2 * 1000
        })
        return
      }
      const data = JSON.stringify(this.calcuTotal())
      const confirmData = {
        selectedSkuItem: this.selectedSkuItem,
        count: 1,
        maskType: 'bonusGift',
        buyType: 'buyBtn',
        buyData: data
      }

      this.$emit('confirm', confirmData)
    },
    showFreightRulePopup(list) {
      this.$emit('ruleControl', list)
    },
    // 去选择规格事件
    goSelSku(index, selSku) {
      if (this.current !== index) return
      this.selectedSkuItem = this.markupGoodses[index].selectedSkuItem
      this.hold = false
      setTimeout(() => {
        this.hold = true
      }, 10)
      if (!this.selectedSkuItem || selSku) {
        this.pShow = true
      }
    },
    selEvent(index) {
      const item = this.markupGoodses[index]
      if (item.status === 5) return
      if ((Math.floor(this.packageTotal.box / item.buy_num) * item.additional_num) === 0) {
        uni.showToast({
          title: '未满足加购条件，请先添加礼包商品',
          icon: 'none',
          duration: 1500
        })
        return
      }
      if (this.current === index) {
        this.current = -1
        this.selGoods = {}
        this.markupGoodses[index].count = 0
        return
      }
      // this.current = index
      this.buyCount = 1
      this.$set(this, 'current', index)
      this.markupGoodses[index].count = 1
      this.selGoods = item
      this.$forceUpdate()
      if (item.sku_list.length === 1) {
        const temp = item.sku_list[0].properties_name.split(';')
        const nameList = []
        temp.map(item => {
          const itemList = item.split(':')
          nameList.push(itemList[1])
        })
        this.markupGoodses[index].skuName = nameList.join('；')
        if (!this.markupGoodses[index].selectedSkuItem) {
          const obj = {
            activity_id: this.selGoods.activity_id,
            selectText: '',
            director_price: this.selGoods.director_price,
            goods_id: this.selGoods.box_id || this.selGoods.goods_id,
            goods_pic: this.selGoods.pic || this.selGoods.image,
            order_limit: item.sku_list[0].order_limit,
            order_min: Math.min(item.sku_list[0].order_limit, item.sku_list[0].num),
            package_goods_number: 1,
            price: this.selGoods.price,
            properties_name: '',
            num: item.sku_list[0].num,
            region_price: this.selGoods.region_price,
            sku_code: item.sku_list[0].sku_code,
            vip_price: this.selGoods.vip_price
          }
          if (obj && obj.order_limit > 0) {
            obj.order_min = Math.min(item.sku_list[0].order_limit, item.sku_list[0].num)
          } else {
            obj.order_min = item.sku_list[0].num
          }
          console.log('obj.order_min', obj.order_min)
          this.markupGoodses[index].selectedSkuItem = obj
        }
      } else {
        this.goSelSku(index)
      }
    },
    alertMax(type) {
      if (type === 'add') {
        const item = this.markupGoodses[this.current].selectedSkuItem || {}
        if (!item) return
        if (item.order_min === item.order_limit) {
          uni.showToast({
            title: '商品限购，无法加购',
            icon: 'none',
            duration: 1500
          })
        } else {
          uni.showToast({
            title: '商品库存不足',
            icon: 'none',
            duration: 1500
          })
        }
      }
    },
    calcuTotal() {
      const array = []
      this.packageTotal.selected.forEach(item => {
        const temp = {
          goods_id: item.goodsId,
          sku_code: item.goodsSkuId,
          bonus_gift_id: this.allData.bonus_gift_id,
          num: item.count,
          goods_type: item.type || 1,
          pack_type: item.packType || 2,
          from_type: this.allData.goods.from_type + ''
        }
        if (item.packageGoodses && item.packageGoodses.length) {
          temp.pack_list = item.packageGoodses.map(el => {
            return {
              sku_code: el.skuCode,
              from_type: 11,
              num: el.packageGoodsNumber
            }
          })
        }
        array.push(temp)
      })
      if (this.current !== -1) {
        const addItem = this.markupGoodses[this.current]
        if (addItem.selectedSkuItem && addItem.selectedSkuItem.order_limit !== 0 && addItem.selectedSkuItem.order_limit < addItem.count) {
          uni.showToast({
            title: `加购商品限购${addItem.selectedSkuItem.order_limit}件`,
            icon: 'none',
            duration: 1500
          })
          return
        }
        if (addItem.selectedSkuItem && addItem.selectedSkuItem.sku_code) {
          const addData = {
            activity_id: '',
            goods_id: addItem.box_additional_id,
            sku_code: addItem.selectedSkuItem.sku_code,
            bonus_gift_id: addItem.bonus_gift_id,
            num: addItem.count,
            goods_type: addItem.goods_type,
            pack_type: addItem.pack_type,
            from_type: '261'
          }
          array.push(addData)
        }
      }
      return array
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
  .box-package {
    height: auto;
    overflow: hidden;
    .h4.title {
      font-size: 14px;
      line-height: 30px;
      margin-top: 10px;
    }
  }
  .total-info {
    position: fixed;
    display: flex;
    justify-content: space-between;
    width: 100%;
    padding: 10px;
    box-sizing: border-box;
    background-color: #FFFDF1;
    left: 0;
    bottom: 120rpx;
    bottom: calc(120rpx + constant(safe-area-inset-bottom));
    bottom: calc(120rpx + env(safe-area-inset-bottom));
    z-index: 9;
    color: #EB5424;
    font-size: 12px;
    .b {
      display: inline-block;
      font-weight: normal;
    }
  }
  .product-info {
    position: relative;
    padding: 15px 0;
    height: auto;
    box-sizing: border-box;
    background-color: #fff;

    .present {
      width: 100%;
      padding: 10px;
      background-color: #FFFDF1;
      color: #EB5424;
      margin-top: 13px;
      font-size: 12px;
      display: block;
      font-weight: normal;
      line-height: 12px;
      margin-bottom: -15px;
      .span {
        display: inline-block;
        line-height: 15px;
        margin-right: 10px;
      }
      .small {
        display: inline-block;
        font-size: 12px;
        .i {
          display: inline-block;
          font-style: normal;
        }
      }
    }
    .clicksc {
      position: absolute;
      right: 0px;
      top: 60px;
    }
    .product-box {
      display: flex;
      .product-img {
        flex: 0 0 70px;
        height: 140rpx;
        position: relative;
        border-radius: 5px;
        overflow: hidden;
        margin-right: 12px;
      }
      .product-intro {
        width: calc(100% - 80px);
        display: flex;
        justify-content: space-between;
        flex-direction: column;
        .p {
          display: block;
          color: $color-text;
          font-weight: bold;
          text-overflow: ellipsis;
          line-height: 38rpx;
          height: 80rpx;
          overflow: hidden;
          display: -webkit-box;
          -webkit-line-clamp: 2;
          -webkit-box-orient: vertical;
          word-break: break-all;
          width: 100%;
          font-size: 28rpx;
        }
        .i {
          display: inline-block;
          color: #999;
          font-size: 12px;
          font-style: normal;
        }
        .small {
          display: inline-block;
          text-decoration: line-through;
          color: #999;
        }
        .b {
          position: relative;
          word-break: break-all;
          margin-right: 90px;
          font-size: 14px;
          display: block;
          font-weight: normal;
          line-height: 12px;
          color: #FF3939;
          padding-bottom: 3px;
          .small {
            display: inline-block;
            font-size: 12px;
          }
          .wh_icon{
            @include extend-click;
            width: 24rpx;
            display: inline-block;
            height: 24rpx;
            margin-left: 16rpx;
            image{
              width: 24rpx;
              height: 24rpx;
            }
          }
        }
      }
    }
  }

</style>
